﻿using System;
using System.Collections.Generic;
using System.Linq;
using Pharmacy.Data;
using Pharmacy.Business.Common;

namespace Pharmacy.Business.Generator
{
    public static class IdentityGeneratorHelper
    {
        /// <summary>
        /// Get next number to generate data for key field of object (SONumber , PONumber, ....)
        /// </summary>
        /// <param name="generatorFullName"></param>
        /// <param name="transDate"></param>
        /// <param name="groupType"></param>
        /// <param name="merchantContext"></param>
        /// <returns></returns>
        public static string GetNextNumber(Pharmacy.Ultilities.Enums.GeneratorObjectType generatorFullName, DateTime? transDate, string groupType, IObjectContext pharmacyContext)
        {
            string type = BOCommon.GetGeneratorTypeName(generatorFullName);
            /******** write code here *********/
            
            try
            {
                //string storeName = string.Format("exec sp_Get_Next_Number '{0}'{1}{2}", type, (transDate.HasValue) ? ",'" + transDate + "'": "", !string.IsNullOrEmpty(groupType) ? ",'" + groupType + "'" : "");
                var nextNumber = pharmacyContext.ExecCommand<string>("exec sp_Get_Next_Number {0},{1},{2}", type, transDate, groupType);
                if (nextNumber == null)
                    return string.Empty;
                
                return nextNumber.AsEnumerable().FirstOrDefault();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            /******** end write code here *********/            
        }

        //public static string GetNextUCC(IObjectContext pharmacyContext)
        //{
        //    string uccCode = GetNextNumber(Pharmacy.Ultilities.Enums.GeneratorObjectType.UCCNoPackGenerator, null, null, pharmacyContext);
        //    if (uccCode.Length < 19)
        //    {
        //        throw new Exception("Can't generate next UCC code");
        //    }

        //    int sum = 0, digit = 0;

        //    for (int i = 1; i <= uccCode.Length; i++)
        //    {
        //        digit = Convert.ToInt32(uccCode.Substring(i - 1, 1));
        //        if (i % 2 == 0)
        //        {	// even
        //            sum += digit * 2;
        //        }
        //        else
        //        {	// odd
        //            sum += digit;
        //        }
        //    }

        //    int checkDigit = sum % 10;
        //    uccCode += checkDigit.ToString();
        //    return uccCode;
        //}       

    }
}
